package cn.nexttec.noteplayer.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.databases.dao.NoteDao
import cn.nexttec.noteplayer.databases.dao.VideoFileDao
import cn.nexttec.noteplayer.injection.IoDispatcher
import cn.nexttec.noteplayer.injection.MainDispatcher
import cn.nexttec.noteplayer.models.NoteFile
import cn.nexttec.noteplayer.models.VideoFileInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(
    val videoFileDao: VideoFileDao,
    val noteDao: NoteDao,
    val preference: Preference,
    @IoDispatcher val ioDispatcher: CoroutineDispatcher,
    @MainDispatcher val mainDispatcher: CoroutineDispatcher
) :ViewModel(){
    private val _fileResult = MutableLiveData<List<VideoFileInfo>>()
    val fileResult:LiveData<List<VideoFileInfo>> get() = _fileResult
    private val _noteResult = MutableLiveData<List<NoteFile>>(emptyList())
    val noteResult:LiveData<List<NoteFile>> get() = _noteResult
    private val _files = MutableLiveData<List<VideoFileInfo>>(emptyList())
    val files:LiveData<List<VideoFileInfo>> get() = _files

    fun searchVideo(keyword:String){
        viewModelScope.launch (ioDispatcher){
            val result = videoFileDao.search(keyword)
            "Search" debug "数据库返回 ${result.size} 条数据"

            withContext(mainDispatcher) {
                _fileResult.value = result.toList() // 保证新引用
            }
        }
    }

    fun searchNote(keyword: String){
        viewModelScope.launch (ioDispatcher){
            val result = noteDao.search(keyword)
            withContext(Dispatchers.Main) {
                _noteResult.value = result
            }
        }
    }

    fun loadDirectory(directory: VideoFileInfo) {
        viewModelScope.launch(ioDispatcher) {
            val fileInfos = videoFileDao.getVideoFilesByPath(directory.path)
            withContext(Dispatchers.Main) {
                _files.value = fileInfos
            }
        }
    }
}